import json
from Simplified_code.fp_obj import fp_obj
import math
import pandas as pd
from os import listdir, makedirs
from os.path import isfile, join, abspath, dirname, exists
import datetime


# 载入配置文件
def load_json_file(path):
    with open(path, 'r') as f:
        dict = json.load(f)
        return dict


# 初始化指纹对象
def init_feature_extractor(params):
    feats = fp_obj(sampling_rate=params['fingerprint']['sampling_rate'],
                   window_length=params['fingerprint']['spec_length'],
                   window_lag=params['fingerprint']['spec_lag'],
                   fingerprint_length=params['fingerprint']['fp_length'],
                   fingerprint_lag=params['fingerprint']['fp_lag'],
                   min_freq=params['fingerprint']['min_freq'],
                   max_freq=params['fingerprint']['max_freq'],
                   nfreq=params['fingerprint']['nfreq'],
                   ntimes=get_ntimes(params))  # ntimes 是啥？
    return feats


# 计算ntimes
def get_ntimes(params):
    n = params['fingerprint']['fp_length']
    return 2 ** (int(math.log(n, 2)))


# 指纹的最小长度
def get_min_fp_length(params):
    return params['fingerprint']['fp_length'] * params['fingerprint']['spec_lag'] + \
           params['fingerprint']['spec_length']


# 读取出csv中数据，同时返回持续时间
def read_csv(path):
    df = pd.read_csv(path, header=None)
    duration = df[1].max() - df[1].min()
    data_list = df[2]
    start_time = df[1].min()
    end_time = df[1].max()
    return data_list, duration, start_time, end_time


# 生成median与mad的存储文件txt
def gen_mad_fname(params):
    mad_folder = params['data']['folder'] + 'mad/'
    init_folder([mad_folder])
    return mad_folder + 'mad%s_%s_%f_%.0f_%s_%s.txt' % (
        params['data']['station'],
        params['data']['channel'],
        params['fingerprint']['mad_sampling_rate'],
        params['fingerprint']['mad_sample_interval'],
        params['data']['start_time'],
        params['data']['end_time'])


# 检查路径是存在，如果不存在就创建
def init_folder(folders):
    for folder in folders:
        if not exists(folder):
            makedirs(folder)


# 创建指纹和时间戳路径
def get_fp_ts_folders(params):
    fp_folder = params['data']['folder'] + 'fingerprints/'
    ts_folder = params['data']['folder'] + 'timestamps/'
    return fp_folder, ts_folder


# 初始化指纹和时间戳文件
def get_ts_fname(mseed_fname):
    idx = mseed_fname.rfind('.')
    return "ts_" + mseed_fname[:idx]


def get_fp_fname(mseed_fname):
    idx = mseed_fname.rfind('.')
    return "fp_" + mseed_fname[:idx]


# 将time_extra加到各分区结尾，因此我们不会丢失任何一段指纹
def get_partition_padding(params):
    sec_extra = params['fingerprint']['spec_length'] + \
                (params['fingerprint']['fp_length'] - params['fingerprint']['fp_lag']) * \
                params['fingerprint']['spec_lag']
    print(sec_extra)
    # time_extra = datetime.timedelta(seconds=sec_extra)
    return sec_extra


def get_combined_fp_name(params):
    final_fp_name = '%s.%s.fp' % (
        params['data']['station'], params['data']['channel'])
    return final_fp_name


def get_combined_ts_name(params):
    final_ts_name = '%s.%s.ts' % (
        params['data']['station'], params['data']['channel'])
    return final_ts_name


def save_fp_stats(params, nfp, ndim):
    fp_stats = {"station": params["data"]["station"],
                "channel": params["data"]["channel"],
                "nfp": nfp,
                "ndim": ndim}
    fname = get_fp_stats_file(params)
    with open(fname, 'w') as f:
        json.dump(fp_stats, f)


def get_fp_stats_file(params):
    return '%s%s_%s.json' % (params["data"]["folder"], params["data"]["station"],
                             params["data"]["channel"])


def get_global_index_dir(param):
    return param["io"]["base_dir"] + param["io"]["global_index_dir"]
